const app = getApp()
import { getAddressList, updateDefaultShippingAddr, postDeleteShippingAddr } from '../../../../api/index'

Page({
  data: {
    list: [],
    isManage: false,
    formPage: '',
    form: '',
    ids: '',
    specKey: '',
    materialId: '',
    num: ''
  },
  selectAddress ({ currentTarget: { dataset: { item } } }) {
    if (this.data.form) {
      if (this.data.form === 'now') {
        wx.$nav.redirectTo(`/pages/account/shopCart/confirm/index?form=${this.data.form}&id=${item.id}&specKey=${this.data.specKey}&materialId=${this.data.materialId}&num=${this.data.num}`)
      } else {
        wx.$nav.redirectTo(`/pages/account/shopCart/confirm/index?form=${this.data.form}&id=${item.id}&ids=${this.data.ids}`)
      }
    }
  },
  toggleStatus () {
    this.setData({ isManage: !this.data.isManage })
  },
  addAddress () {
    wx.$nav.navigateTo(`/pages/account/address/edit/index`)
  },
  edit ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/account/address/edit/index?id=${item.id}`)
  },
  async changeAddress ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '修改默认地址', content: '确定要设置该地址为默认地址吗？' })
      if (confirm) {
        await updateDefaultShippingAddr({ id: item.id })
        wx.showToast({ title: '设置成功！', icon: 'none' })
        this.getList()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async delAddress ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '删除地址', content: '确定要删除该地址吗？' })
      if (confirm) {
        await postDeleteShippingAddr({ id: item.id })
        wx.showToast({ title: '设置成功！', icon: 'none' })
        this.getList()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getList () {
    try {
      const { ResultSet } = await getAddressList()
      this.setData({ list: ResultSet.userData.data })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ form, formPage, ids, specKey, materialId, num }) {
    if (form) this.setData({ form })
    if (formPage) this.setData({ formPage })
    if (ids) this.setData({ ids })
    if (specKey) this.setData({ specKey })
    if (materialId) this.setData({ materialId })
    if (num) this.setData({ num })
  },
  onShow () {
    this.getList()
  }
})